﻿using System;
using System.Threading;
using Com.PhilChuang.Pmvp.Utils;
using Com.PhilChuang.Utils;
using Com.PhilChuang.Utils.Mobile;
using LearningWindowsPhone.RunUnderLock;

namespace Com.PhilChuang.Mobile.Apps.LocationSender.Model
{
	public class LocationSenderAppHelper : DefaultAppHelper
	{
		public LocationSenderAppHelper ()
		{
		}

		private static void InitAppAsync ()
		{
			var app = AppServiceLocator.Instance.GetImpl<LocationSenderApp> (); // this is done to ensure that the app is instantiated before returning flow control
			ThreadPool.QueueUserWorkItem (
				obj =>
				{
					if (!app.IsInitialized) app.Init (false);
					AppServiceLocator.Instance.GetImpl<NavigationHelper> ().WaitForCurrentPage ().Dispatcher.BeginInvoke (InitApplicationIdleModeHelper);
				});
		}

		private static void InitApplicationIdleModeHelper ()
		{
			ApplicationIdleModeHelper.Current.Initialize ();
			if (ApplicationIdleModeHelper.Current.HasUserAgreedToRunUnderLock)
				ApplicationIdleModeHelper.Current.RunsUnderLock = true;
		}

		public override void OnAppLaunch ()
		{
			LaunchStatus = AppLaunchStatus.IsFresh;
			InitAppAsync ();

			FireLaunching ();
		}

		public override void OnAppResume ()
		{
			LaunchStatus = AppLaunchStatus.IsResume;
			InitAppAsync ();

			FireResuming ();
		}

		public override void OnUnhandledException (object sender, HandledEventArgs<Exception> e)
		{
			if (e.Item is ForceExitException)
				return; // ignore
			base.OnUnhandledException (sender, e);
		}

		public override void ForceExit ()
		{
			throw new ForceExitException ();
		}
	}

	public class ForceExitException : Exception
	{
	}
}
